package com.authine.cloudpivot.web.api.controller;

import net.sf.json.JSONObject;
import com.authine.cloudpivot.web.Utils.InterfaceDockingUtil;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.domain.dto.CustomerDTO;
import com.authine.cloudpivot.web.api.domain.dto.InterfaceDTO;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.service.CustomerService;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "外企德科相关接口", tags = "客户信息")
@RestController
@RequestMapping("/api/customer")
@Slf4j
@Validated
@Component
public class CustomerController extends BaseController {

    @Value("${address.customerUrl}")
    private String customerUrl;
    @Value("${address.secretKey}")
    private String secretKey;

    @Autowired
    private  CustomerService  customerService;

    /**
     * @Description : 对方主动调用我方系统接口
     * @param ： customerDTO
     * @author : Liun
     * @date : 2020/4/30
     * @Valid @RequestBody CustomerDTO customerDTO
     */
    @ApiOperation(value = "生成客户信息" )
    @PostMapping("/customerInformation")
    @ResponseBody
    public ResponseResult<?> customerInformation(@Valid @RequestBody InterfaceDTO InterfaceDTO){
        JSONObject json = new JSONObject();
        Long statusReal = 200L;
        try {
            String sig=InterfaceDTO.getSig();
            String secretKey="df7632kjdf";
            String realSig=InterfaceDockingUtil.createSig(InterfaceDTO.getUser_key(),InterfaceDTO.getData(),InterfaceDTO.getCall_time(),secretKey);
            if(sig.equals(realSig)){
                String data=InterfaceDTO.getData();
                JSONObject dataJson = JSONObject.fromObject(data);
                Map<String,Object> dataMap=(Map)dataJson;
                CustomerDTO customerDTO=(CustomerDTO)dataMap.get("params");
                List<CustomerDTO>  customerDTOList=new ArrayList<>();
                customerDTOList.add(customerDTO);
                customerService.customerInformation(customerDTOList);
                json.put("message","生成客户信息成功");
            }else{
                throw new PortalException(500L,"sig认证失败");
            }
        }catch (PortalException e) {
                statusReal = 500L;
                json.put("message", "生成客户信息失败：" + e.getErrMsg());
        }catch (Exception e){
                statusReal = 500L;
                json.put("message", "sig认证失败");
        }
        return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
    }


   /**
    * @Description : 定时获取客户信息（我方拉取对方信息）
    * @param ：
    * @author : Liun
    * @date : 2020/5/8
    */
    @Scheduled(cron = "0 55 23 ? * *")
    //@Scheduled(cron = "0 0/4 * ? * *")
    public void getCustomerByTiming(){
        try{
            this.getCustomerTotalCount();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * @Description :  手动同步客户信息（我方拉取对方信息）
     * @param ：
     * @author : Liun
     * @date : 2020/5/22
     */
    @ApiOperation(value = "同步客户信息" )
    @PostMapping("/getCustomerByManual")
    @ResponseBody
    public ResponseResult<?> getCustomerByManual(){
        JSONObject json = new JSONObject();
        Long statusReal = 200L;
        try {
            this.getCustomerTotalCount();
        }catch (PortalException e) {
            statusReal = 500L;
            json.put("message", "生成客户信息失败：" + e.getErrMsg());
        }catch (Exception e){
            statusReal = 500L;
            json.put("message", "生成客户信息失败：" + e.getMessage());
        }
        return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
    }



    /**
     * @Description : 获取客户信息
     * @param ：
     * @author : Liun
     * @date : 2020/5/22
     */
    public void getCustomerTotalCount() throws Exception{
        Map<String,Object> customerResult =  this.getCustomerResult(1);
        Map<String, Object> dataMap=new HashMap<>();
        if((Boolean) customerResult.get("success")&& ObjectUtils.allNotNull(customerResult.get("dataList"))) {
            dataMap = getDataListMap(customerResult);
        }
        int totalPages=0;
        if(ObjectUtils.allNotNull(dataMap)){
            totalPages= Integer.parseInt(dataMap.get("totalPages").toString());
        }
        if(totalPages==1){
            List<CustomerDTO>  customerDTOList=  getCustomer(customerResult);
            //生成客户信息
            customerService.customerInformation(customerDTOList);
        }else if(totalPages>1){
            //分页获取客户信息
            Map<String,Object> customerResults;
            List<CustomerDTO>  customerDTOLists;
            for(int i=1;i<=totalPages;i++){
                customerResults = this.getCustomerResult(i);
                customerDTOLists = this.getCustomer(customerResults);
                //生成客户信息
                customerService.customerInformation(customerDTOLists);
            }
        }
    }


    /**
     * @Description : 调用第三方接口，获取客户信息
     * @param ： pageNo
     * @author : Liun
     * @date : 2020/5/8
     */
    public Map<String,Object>  getCustomerResult(int pageNo) throws Exception {
        //创建连接对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //post请求
        HttpPost httpPost = new HttpPost(customerUrl);

        Map<String,Object> customerResult = new HashMap<>();
        try {
            //封装请求参数
            Map<String,String> rm = InterfaceDockingUtil.getSecretParams(pageNo,secretKey);
            List<NameValuePair> list = new ArrayList<>();
            for(Map.Entry<String,String> entry : rm.entrySet()){
                NameValuePair valuePair = new BasicNameValuePair(entry.getKey(),entry.getValue());
                list.add(valuePair);
            }
            //请求报文，参数格式
            httpPost.addHeader("Content-type","application/x-www-form-urlencoded");
            httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
            log.info("<<==========  正在连接pass接口 ==========>>");
            HttpResponse response = httpClient.execute(httpPost);
            log.info("<<==========  连接pass接口成功 ==========>>");
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //成功后响应数据
                String  result= EntityUtils.toString(response.getEntity());
                log.info("获取到的客户信息-----------------》"+result);
                JSONObject json = JSONObject.fromObject(result);
                customerResult=(Map)json;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            try {
                //释放连接
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return customerResult;
    }

    /**
     * @Description : 获取客户信息后转换成本系统客户信息
     * @param ：
     * @author : Liun
     * @date : 2020/5/8
     */
    public List<CustomerDTO> getCustomer(Map<String,Object> customerResult){
        List<CustomerDTO> customerDTOList = new ArrayList<>();
        String status="success";
        if((Boolean) customerResult.get("success")&& ObjectUtils.allNotNull(customerResult.get("dataList"))){
            Map<String,Object> dataMap= getDataListMap(customerResult);
            if(status.equals(dataMap.get("status").toString())&& ObjectUtils.allNotNull(dataMap.get("result"))){
                JSONArray jsonResult =(JSONArray)dataMap.get("result");
                customerDTOList = JSONArray.toList(jsonResult, new CustomerDTO(), new JsonConfig());
            }
        }
        return customerDTOList;
    }

    /**
      * @Description : 获取具体数据转换为Map
      * @param ： customerResult
      * @author : Liun
      * @date : 2020/5/26
      */
     public Map<String,Object> getDataListMap(Map<String,Object> customerResult){
         Map<String, Object> dataMap=new HashMap<>();
         if((Boolean) customerResult.get("success")&& ObjectUtils.allNotNull(customerResult.get("dataList"))) {
             JSONObject jsonData = JSONObject.fromObject(customerResult.get("dataList").toString());
             dataMap = (Map) jsonData;
         }
         return dataMap;
     }
}
